const roleControllers = require("../controllers/roleControllers");

global.service_caches = {};
global.service_rights = [];
global.service_function = {
	GET:1,
	POST:2,
	PUT:4,
	DELETE:8
}

/**
 * 构造回调对象格式
 * 
 * @param {[type]} serviceName   服务名称
 * @param {[type]} actionName    动作名称（方法名）
 * @param {[type]} serviceModule 服务模块
 * @param {[type]} origFunc      原始方法
 */
async function invocation(path) {
	let roleRights = await roleControllers.selectAllRoleRights();
	let temp = {};
	roleRights.forEach(item=>{
		if(!temp[item.role_id]){
			temp[item.role_id] = {};
		}
		temp[item.role_id][ path+item.right_api ] = item.right_function;
	})
	global.service_caches = temp;
}
module.exports.invocation = invocation;
// 设置全局验证函数
// 某些接口仅需登录即可，不需要基于功能点的二次权限校验
const AUTH_WHITELIST = [
	'/api/v1/menus',           // 获取当前用户菜单
	'/api/v1/auth',            // 通用的选项/角色等查询
	'/api/v1/admin/stats'      // 管理员首页统计
];

module.exports.checkAuth = function(req,res,next){
	// 白名单放行：仅做登录校验，不做功能点校验
	for (const w of AUTH_WHITELIST) {
		if (req.path === w || req.path.startsWith(w + '/')) {
			next();
			return;
		}
	}
	if(!global.service_rights.includes(req.path)){
		next();
		return
	}

	let { role_id } = req.auth;
	let roleRights = global.service_caches[role_id];
	
	if(roleRights==null){
		res.sendResult(null,403,"禁止访问");
		return;
	}

	let authNum = null;
	for (let key in roleRights) {
		if( req.path.startsWith(key) ){
			authNum = roleRights[key];
			break;
		}
	}	
	let gnum = global.service_function[req.method];
	if( authNum==null || ((authNum & gnum)!=gnum) ){
		res.sendResult(null,403,"未授权");
		return;
	}

	next()
};

